package com.lagou.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
;

public class CreateTable {

    Configuration conf = null;
    Connection conn = null;
    HBaseAdmin admin = null;

    @Before
    public void init() throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "linux01,linux02");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    @After
    public void destroy() {
        if (null != admin) {
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != conn) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 需求1：使用HBase相关API创建一张rowkey为用户uid、
     * <p>
     * 列族friends列名为好友的uid（列值同样为uid）的表
     */
    @Test
    public void createTable() throws IOException {
        //获得admin对象
        admin = (HBaseAdmin) conn.getAdmin();
        //创建表描述器
        HTableDescriptor relations = new HTableDescriptor(TableName.valueOf("relations"));
        //设置列族描述器
        relations.addFamily(new HColumnDescriptor("friends"));
        //创建表
        admin.createTable(relations);
        System.out.println("relations表创建成功");

    }

    public void putData(String userA, String userB) throws IOException {
        //获取表对象
        Table relations = conn.getTable(TableName.valueOf("relations"));
        //获取put对象
        Put put = new Put(Bytes.toBytes(userA));
        //friends列族中加入“列”及“value”
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes(userB), Bytes.toBytes(userB));
        //执行插入
        relations.put(put);
        //关闭表对象
        relations.close();
        System.out.println("插入成功!!!");
    }

    @Test
    public void addData() throws IOException {
        //插入数据
        putData("uid1", "uid2");
        putData("uid1", "uid5");
        putData("uid1", "uid7");
        putData("uid2", "uid1");
        putData("uid2", "uid3");
        putData("uid2", "uid6");
    }
}
